package com.zstk.example.config.mybatisplus;


import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;

import org.apache.ibatis.reflection.MetaObject;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * MybatisPlus提供的自动填充的辅助配置类
 *
 * @author zstk-colin
 * @since 2019/10/11 9:57
 */
@Component
@ConditionalOnClass(SysMetaObjectHandler.class)
public class SysMetaObjectHandler implements MetaObjectHandler {
    private static final String CREATE       = "createTime";
    private static final String UPDATE       = "updateTime";
    private static final String TOKEN        = "token";
    public static final  String DELETED      = "deleted";
    public static final  String DELETED_FLAG = "0";

    @Override
    public void insertFill(MetaObject metaObject) {
        if (metaObject.hasSetter(CREATE)) {
            setFieldValByName(CREATE, LocalDateTime.now(), metaObject, FieldFill.INSERT);
        }
        if (metaObject.hasSetter(UPDATE)) {
            setFieldValByName(UPDATE, LocalDateTime.now(), metaObject, FieldFill.INSERT_UPDATE);
        }
        if (metaObject.hasSetter(DELETED)) {
            setFieldValByName(DELETED, DELETED_FLAG, metaObject, FieldFill.INSERT);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        if (metaObject.hasSetter(UPDATE)) {
            //如果是登录时自动更新token,则不自动插入更新时间
            boolean isToken = (metaObject.hasSetter(TOKEN) && getFieldValByName(TOKEN, metaObject) == null);
            if (!metaObject.hasSetter(TOKEN) || isToken) {
                setFieldValByName(UPDATE, LocalDateTime.now(), metaObject, FieldFill.INSERT_UPDATE);
            }
        }
    }
}
